import axios from 'axios'
import router from '@/router'
import { getToken } from '@/utils/auth'

// 创建一个 axios 实例
const service = axios.create({
  headers: {
    post: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*'
    }
  },
  withCredentials: true,
  timeout: 30000 // 请求超时时间
})

function pushAjaxQueue(config) {
  if (config && config.loadingLoader) {
    window.$wait.start(config.loadingLoader)
  }
}

function popAjaxQueue(config) {
  /** 清除该请求的loading载体 */
  if (config && config.loadingLoader) {
    window.$wait.end(config.loadingLoader)
  }
}

service.interceptors.request.use(
  config => {
    const authorization = getToken()
    if (authorization) {
      config.headers.authorization = authorization
    }
    pushAjaxQueue(config)
    return config
  },
  err => {
    popAjaxQueue(err.config)
    return Promise.reject(err)
  }
)
service.interceptors.response.use(
  response => {
    popAjaxQueue(response.config)
    return response
  },
  error => {
    popAjaxQueue(error.config)
    let errorMsg = '请求出错啦'
    if (error.response) {
      switch (error.response.status) {
        case 400: errorMsg = '请求错误'; break
        case 401:
          router.replace({
            path: '/login'
          })
          errorMsg = '未授权，请登录'
          break
        case 403: errorMsg = '拒绝访问'; break
        case 404: errorMsg = `请求地址出错: ${error.response.config.url}`; break
        case 408: errorMsg = '请求超时'; break
        case 500: errorMsg = '服务器内部错误'; break
        case 501: errorMsg = '服务未实现'; break
        case 502: errorMsg = '网关错误'; break
        case 503: errorMsg = '服务不可用'; break
        case 504: errorMsg = '网关超时'; break
        case 505: errorMsg = 'HTTP版本不受支持'; break
        default: errorMsg = '服务器出错，请重试!'; break
      }
    } else {
      errorMsg = '当前网络不可用,请检查网络连接情况'
    }
    return Promise.reject(errorMsg)
  }
)

// 替换URL参数(重要，不要删除该方法)
export function dealApiParams(apiUrl, params) {
  const reg = /{.*?}/g
  const matchResult = apiUrl.match(reg)
  // 如果匹配
  if (matchResult) {
    matchResult.forEach(match => {
      const replaceReg = /[{}]/g
      // 变量值
      const variate = match.replace(replaceReg, '')
      apiUrl = apiUrl.replace(match, params[variate])
    })
  }
  return apiUrl
}

export const apiGet = async(url, data, config) => {
  url = dealApiParams(url, data)
  const result = await service.get(url, {
    params: data,
    ...config
  })
  return result
}

export const apiPost = async(url, data, config) => {
  url = dealApiParams(url, data)
  const result = await service.post(url, data, config)
  return result
}

export const apiPut = async(url, data, config) => {
  url = dealApiParams(url, data)
  const result = await service.put(url, data, config)
  return result
}

export const apiDelete = async(url, data, config) => {
  url = dealApiParams(url, data)
  const result = await service.delete(url, {
    data,
    ...config
  })
  return result
}
